/**
 * 标签页的View定义，View路径：module/component/views/TreeView
 * @class ngc.component.view.TabView
 */
define(
		[ "module/component/views/CommonUIView" ],
		function(CommonView) {
			var _attachTabTemplate = '<div id="{{id}}" class="{{#if type}}{{type}} {{/if}} tabs_nav ui-tabs res_component_tab"> <ul class="tabs_nav_list ui-tabs-nav"></ul></div>';			
			var tabView = CommonView
					.extend({
						template: ngc.compile(_attachTabTemplate),
						serialize:function(){
							var _obj_id = this._obj_id = ngc.getUUID();
							var _data = {id:_obj_id}
							if(this.getOptionConfig()&&this.getOptionConfig().type){
								_data.type = this.getOptionConfig().type;
							}
							return _data;
						},
						tabAnimate: function (e) {
							
					            var $target = $(e.target);
					            if ($target.is('span') || $target.is('a')) { //转成<a>
					                $target = $target.closest("li");
					            }
					            //点击效果---begin
					            var parent = $target.parent();

					            if(parent&&parent.offset()){
					            	if (parent.find("span.ink").length === 0) {
						                parent.prepend("<span class='ink '></span>");
						                setTimeout(function () {
						                    parent.find("span.ink").remove();
						                }, 500);

						            }

						            var ink = parent.find(".ink");

						            ink.removeClass("animate");

						            if (!ink.height() && !ink.width()) {
						                var d = Math.min(parent.parent().outerWidth(), parent.parent().outerHeight());
						                ink.css({height: d, width: d});
						            }

						            var x = e.pageX - parent.offset().left - ink.width() / 2;
						            var y = e.pageY - parent.offset().top - ink.height() / 2;

						            ink.css({top: y + 'px', left: x + 'px'}).addClass("animate");
					            }
					            
					            //---end
					        },
						afterRender : function() {	
							
							var _tab_config = 
								$.extend( {canClose:true,
						              paging: true,
						              autoResizable:true,
						              remove: function(e, ui) {
						                 this._isShow();
						              }.bind(this)
								},this.getOptionConfig()),that = this;
							
							
							
							this.getComponentObject().tabs(_tab_config);							
							
							 this._resizeHandler = ngc.onResize(function(){
								 that.autoResize();								 
								 var tabs = that.getAllTabs();
								 $.each(tabs,function(){
									 if(this.hasClass("ui-tabs-active")){
										 var rel_id = this.children('a').attr("href");
										 if(that.$(rel_id).is(':visible')){
											 that.setFixedTabHeight(rel_id,true);
											 that.doTabDocumentResize(rel_id,true);
										 }										 
									 }
								 })
							 });
							 that.autoResize();
							 this.setInitFlag(true);
							 this.getComponentObject().delegate("ul:first .ui-tabs-anchor","click",this.tabAnimate);
							 this.trigger("viewRenderAfter");
						},	
						
						_refreshAllTabViews:function(){
							var tabs = this.getAllTabs(), that = this;
							 $.each(tabs,function(){
								 if(this.hasClass("ui-tabs-active")){
									 var rel_id = this.children('a').attr("href");
									 if(that.$(rel_id).is(':visible')){
										 that.setFixedTabHeight(rel_id,true);
										 that.doTabDocumentResize(rel_id,true);
									 }										 
								 }
							 })
						},
						
						_getMenuClickObj:function(){
							return this.getComponentObject().children("ul.ui-tabs-nav");
						},
						
						/**
						 * @event onClickMenu
						 * @param {String} id 点击的菜单项ID
						 * @param {Object} param 相关参数 
						 * @param {Object} menu  菜单对象
						 */
						onMenuEvent:function(id,menu,param){
							this.trigger('onClickMenu',id,param,menu);
							
						},
						_getRelTabId:function(id){
							return this._obj_id+"_"+id;
						},
						/**
						 * @method 激活标签页
						 * @param {String} id:要激活的标签页ID
						 */
						activeTab:function(id){
							this.getComponentObject().tabs("option", "active", this._getRelTabId(id)); 
						},
						
						
						/**
						 * @method 根据标签页ID/序号，获取标签页序号/ID
						 * @param {Number|String} index 移除的标签页ID或者标签页序号
						 * @return {Number|String} 返回标签页ID/序号
						 */
						getTabIdIndex:function(index){
							var tabs = this.getAllTabs(), that = this, _rst;
							 $.each(tabs,function(i){
								 var _relId = this.children('a').attr("href");
								 if(_relId.indexOf("#"+that._obj_id+"_")!=-1){
									var id = _relId.replace("#"+that._obj_id+"_",""); 
									if(ngc.isNumber(index)&&index===i){
										_rst = id;
										return false;
									}else if(id===index){
										_rst = i;
										return false;
									}
								 }
							 });
							 return _rst;
						},

						/**
						 * @method 新增标签页
						 * @param {String} id:新增的标签页ID，保证在当前的TabView对象内唯一
						 * @param {String} label：新增的标签页名称
						 * @param {Boolean}  active:可选，是否激活标签页，true-激活，false或忽略则不激活
						 * @param {Number} index：可选，新增标签页的位置
						 * @param {String} content：可选，新增标签页的内容
						 */
						addTab : function(id, label, active, index, content) {
							var that = this;
							this.getComponentObject().tabs("add", {
								"active" : active,
								"id" : that._getRelTabId(id),
								"index" : index,
								"content" : content,
								"label" : label
							});
							this._isShow();
						},

						/**
						 * @method 移除标签页
						 * @param {Number|String} index 移除的标签页ID或者标签页序号
						 */
						removeTab : function(index) {
							if(ngc.isNumber(index)){
								index = this.getTabIdIndex(index);
							}
							if(this.getTabViewObj(index)){
								this.removeView(this._getRelTabId(index));
							}							
							this.getComponentObject().tabs("remove", this._getRelTabId(index));
							this._isShow();
						},
						
						_isShow:function(before){
							if(this.getOptionConfig()&&this.getOptionConfig().oneIsHidden==true){
								var tabs = this.getAllTabs(false);
								var count = tabs.length;
								if(before==true){
									count = --count;
								}
								if(count<=1){
									this.getComponentObject().children("ul").hide();
								}else{
									this.getComponentObject().children("ul").show();
								}
								
							}
						},
						
						/**
						 * 禁用标签页
						 * @method disable
						 * @param {String} id :禁用的标签页ID
						 */
						disable : function(index) {
							this.getComponentObject().tabs("disable", this._getRelTabId(index));
						},
						/**
						 * 启用标签页
						 * @method enable
						 * @param {String} id :启用的标签页ID
						 */
						enable : function(index) {
							this.getComponentObject().tabs("enable", this._getRelTabId(index));
						},
						
						/**
						 * 获取标签页长度
						 * @method getSize
						 * @return {Number}
						 */
						getSize : function() {
							return this.getComponentObject().tabs("getSize");
						},
						/**
						 * 隐藏标签页
						 * @method hideTab
						 * @param {String} id :标签页在当前标签内全局唯一ID
						 */
						hideTab : function(index) {
							this.getComponentObject().tabs("hideTab",this._getRelTabId(index));
							this._isShow();
						},
						/**
						 * 显示标签页
						 * @method showTab
						 * @param {String} id :标签页在当前标签内全局唯一ID
						 */
						showTab : function(index) {
							this.getComponentObject().tabs("showTab",this._getRelTabId(index));
							this._isShow();
						},
						
						_openTab:function(tabId, label, taburl, active, closed){
							if(this.$("#"+this._getRelTabId(tabId)).length>0){
								this.activeTab(tabId);
								return true;
							}
														
							
							if(closed===false||closed===true){
								this.getComponentObject().tabs("option","canClose",closed);
							}
							var tmpLabel = label;
							if(this.getOptionConfig()&&this.getOptionConfig().labelSize&&ngc.isNumber(parseInt(this.getOptionConfig().labelSize))){
								var tmpLabel = ngc.subStringByChar(label,parseInt(this.getOptionConfig().labelSize));
								if(tmpLabel.length!=label.length){
									tmpLabel = tmpLabel +'...';
								}
							}
							
							var that=this,$tpl = $("<div>").data({
								tabId: tabId,
			                    taburl: taburl,
			                    tabName: label
			                }).attr({tabId: tabId,taburl: taburl});
							this.getComponentObject().tabs("option", "panelTemplate", $tpl).tabs("add", {
			                    active: active,
			                    id: that._getRelTabId(tabId),
			                    label: tmpLabel
			                });
							
							this.setFixedTabHeight(tabId);
							this._isShow();
						},
						
						/**
						 * 获取Tab页上的视图对象
						 * @param {String} tabId 初始化标签页在当前标签内全局唯一ID
						 * @return {Object} 如果存在视图对象，则返回值为视图对象
						 */
						getTabViewObj:function(tabId){
							return this.getView("#"+this._getRelTabId(tabId));
						},

						/**
						 * 打开标签页，使用require的方式打开
						 * @method openView
						 * @param {String} tabId 标签页在当前标签内全局唯一ID
						 * @param {String} label 标签页显示名称
						 * @param {String} taburl 标签页加载的View的url
						 * @param {Boolean} [active] 可选，是否激活当前标签页
						 * @param {Boolean} [closed] 可选，是否可关闭，true-可关闭；false-不可关闭
						 * @param {Object} [params] 可选，传递给视图的参数
						 * @param {Function} [params.callback] 可选，视图打开渲染完成之后的回调函数
						 */
						openView: function (tabId, label, taburl, active, closed, params){
							
							var _oldFlag = this.getComponentObject().tabs("option").canClose,
								_rst = this._openTab(tabId, label, taburl, active, closed),
								that = this;
							
							if(_rst)return;
							if(!params){
								params = {};
							}
							$.extend(params,{el:"#"+that._getRelTabId(tabId)});
							that.requireView({selector:"#"+that._getRelTabId(tabId),url:taburl,viewOption:params}).then(function(){								
								
								if (params&&ngc.isFunction(params.callback)) {
	                                        params.callback.call(that.getView("#"+that._getRelTabId(tabId)), this);
	                            }
								that.doTabDocumentResize(tabId);
							});
							
							this.getComponentObject().tabs("option","canClose",_oldFlag);
							
						},
						
						/**
						 * 打开标签页，使用require的方式打开
						 * @method openViewObject
						 * @deprecated 请使用openView
						 * @param {String} tabId 标签页在当前标签内全局唯一ID
						 * @param {String} label 标签页显示名称
						 * @param {String} viewObj 标签页加载的View对象
						 * @param {Boolean} [active] 可选，是否激活当前标签页
						 * @param {Boolean} [closed] 可选，是否可关闭，true-可关闭；false-不可关闭
						 */
						openViewObject: function (tabId, label, viewObj, active, closed){
							
							var _oldFlag = this.getComponentObject().tabs("option").canClose,
								_rst = this._openTab(tabId, label, ngc.getUUID(), active, closed),
								that = this;
							
							if(_rst)return;
							
							this.setView("#"+that._getRelTabId(tabId),viewObj);
							
							this.renderViews("#"+that._getRelTabId(tabId));
							
							this.getComponentObject().tabs("option","canClose",_oldFlag);
							
						},
						
						
						/**
						 * 打开标签页，使用Iframe的方式打开
						 * @method openFrameView
						 * @param {String} tabId 标签页在当前标签内全局唯一ID
						 * @param {String} label 标签页显示名称
						 * @param {String} taburl 标签页打开的url地址
						 * @param {Boolean} [active] 可选，是否激活当前标签页
						 * @param {Boolean} [closed] 可选，是否可关闭，true-可关闭；false-不可关闭
						 * @param {Object} [params] 可选，传递给视图的参数
						 * @param {Function} [params.callback] 视图打开渲染完成之后的回调函数
						 */
						openFrameView: function (tabId, label, taburl, active, closed, params){
							var _oldFlag = this.getComponentObject().tabs("option").canClose,
								_rst = this._openTab(tabId, label, taburl, active, closed),
								that = this;
						
							if(_rst)return;
							require(["module/component/views/IframView"], function (View) {
	                        	ngc.isString(params) ? params = {_src:params}:"";
	                            var view = new View(params);//iframe的params直接挂到原url后面
	                            view.$el.parent().addClass("no-padding tabs__content");//区分commonView

	                            that.setView("#"+that._getRelTabId(tabId), view);//移除旧的替换成新的,参数为params为options对象
	                            that.renderViews("#"+that._getRelTabId(tabId));//调用render方法

	                            var oldUrl = params._src ? taburl +"?"+ params._src : taburl;
	                            view.$el.attr("src", oldUrl ).ready(function () {
                                    if (ngc.isFunction(params.callback)) {
                                        params.callback.call(view, params);
                                    }
                                    
                                });
	                            
	                        });
							this.getComponentObject().tabs("option","canClose",_oldFlag);
						},	
						
						/**
						 * 设置整个标签页组件的高度
						 */
						autoResize:function(){
							var $el = this.getComponentObject();
			                $el.css("overflow-y", 'auto');
			                $el.css("overflow-x", 'hidden');
				            var height = $el.parent().height() - (ngc.isIE ? 3 : 0);
				            $el.outerHeight(height);
						},
						
						
						 resizeTab: function (tabId) {
							 this.setFixedTabHeight(tabId);
					     },
					     
					     isActive:function(tabId){
					    	 var tabObj = this.$('#'+this._getRelTabId(tabId));
					    	 if(tabObj.css("display")=='none'){
					    		 return false;
					    	 }else{
					    		 return true;
					    	 }
					     },
					      

					      /**
					       * 设置标签页内部view高度,参数为当前标签页的高度
					       */
					      doTabDocumentResize:function(tabId,relFlag){
					    	  var viewObj = this.getTabViewObj(tabId);
					    	  if(relFlag===true){
					    		  viewObj = this.getView(tabId);
					    	  }else{
					    		  tabId = '#'+this._getRelTabId(tabId);
					    	  }
					    	  var $tabDiv = this.$(tabId);
					    	  if(viewObj&&ngc.isFunction(viewObj.resize)){
					    		  var $obj = viewObj.$el;
					              var delta = $obj.parent().height();
					              viewObj.resize($tabDiv.height(),delta);
					    	  } 
					      },
					      
					      /**
					       * 设置指定标签页页面高度
					       */
					      setFixedTabHeight: function (tabId,relFlag) {
					    	  if(relFlag!==true){
					    		  tabId = '#'+this._getRelTabId(tabId);
					    	  }
					    	  var $tabDiv = this.$(tabId);
					    	  $tabDiv.css("overflow-y", 'auto');
					          $tabDiv.css("overflow-x", 'hidden');
					          var height = $tabDiv.parent().innerHeight() - $tabDiv.parent().children('.ui-tabs-nav').outerHeight(true)- (ngc.isIE ? 3 : 0);
					          $tabDiv.outerHeight(height);
					     },

					  
						/**
						 * 获取所有标签页对象
						 * @param {Boolean} includeHidden 是否包含隐藏的标签页
						 * @param {Boolean} includeDisabled 是否包含禁用的标签页
						 * @return {Array}
						 */
						getAllTabs : function(includeHidden, includeDisabled) {
							return this.getComponentObject().tabs("getAllTabs",
									includeHidden, includeDisabled);
						}

					})
					
					return tabView;

		})